package com.yamibuy.ec.resource.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.yamibuy.ec.resource.domain.Coder;
import com.yamibuy.ec.resource.domain.Result;
import com.yamibuy.ec.resource.exception.PathUnknowException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

/**
 * 异常处理返回
 *
 * @author: damon.li
 * @version: 2021年02月23日 8:33
 */
@Component
@Slf4j
public class ExceptionHandler implements RequestHandler<Exception> {

	@Override
	public ByteArrayOutputStream handle(Exception e) throws Exception {
		String simpleMessage = ExceptionUtil.getSimpleMessage(e);
		String message = ExceptionUtil.getMessage(e);
		log.error("resource 异常：{}", message);

		Result result;
		if (e instanceof AmazonS3Exception) {
			AmazonS3Exception amazonS3Exception = (AmazonS3Exception) e;
			int statusCode = amazonS3Exception.getStatusCode();
			if (statusCode == 404) {
				result = Result.no(Coder.System.NOT_FOUND_IMG, simpleMessage);
			} else {
				result = Result.no(Coder.System.Amazon_S3_Exception, simpleMessage);
			}
		} else if(e instanceof PathUnknowException){
			result = Result.no(Coder.System.PATH_UNKONW, simpleMessage);
		}else {
			result = Result.no(Coder.System.ERROR, simpleMessage);
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		IoUtil.write(out, Charset.defaultCharset().name(), true, new JSONObject(result).toString());
		return out;
	}
}
